
let fs = require('fs');
let path = require('path');
let _ = require('underscore');

let handler = function (req, res) {
    fs.readFile(path.join(__dirname + '/index.html'),
        function (err, data) {
            if (err) {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }

            res.writeHead(200, { 'content-type': 'text/html' });

            res.end(data);
        });
}
let app = require('http').createServer(handler)
let io = require('socket.io')(app);

let hasName = new Array();

app.listen(8081);

io.on('connection', function (socket) {
    console.log('connection is established!');
    socket.on('setName', function (data) {
        var name = data;
        hasName[name] = socket.id;
        console.log(hasName);
    })
    socket.on('sayTo', function (data) {
        let toName = data.to;
        let toId;
        if (toId = hasName[toName]) {
            let toSocket = _.findWhere(io.sockets.sockets, { id: toId });
            toSocket.emit('message', data.msg);
            console.log('==================');
            console.log('to ' + toName, data.msg);
            console.log('==================');
        }
    })
    socket.on('disconnect', function () {
        console.log('connection is disconnect!');
    })
});

let sendUserMsg = function (data) {
    if (data.to in usocket) {
        console.log('*********************');
        console.log('to' + data.to, data);
        usocket[data.to].emit('to' + data.to + data);
        usocket[data.users].emit('to' + data.user, data);
        console.log('*********************');
    }
}



// module.exports = output;
